package de.gora.prog2swing.adventskalender.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

/**
 * Used to read .csv files. Decorates the BufferedReader class. 
 * @author Marco Gora
 * @version Java 7u5, Eclipse Juno (4.x)
 */
public class CsvReader {
	
	private BufferedReader stream;
	private static CsvReader instance;
	
	private CsvReader(){
		try{
			this.stream = new BufferedReader(new FileReader(new File("./questions/questions.csv")));
		} catch(FileNotFoundException e){
			
		}
	}
	
	/**
	 * Reads the question file line by line and stores its content in a two-dimensional array.
	 * @return a list of questions. Those questions are stored in an array of String. Where
	 * the 0-index is the question itself, the 1-, 2- and 3-index are the available answers
	 * and the 4 index is the correct answer.
	 * @throws IOException
	 */
	public LinkedList<String[]> readFile() throws IOException{
		LinkedList<String[]> list = new LinkedList<String[]>();
		String[] lineItems = new String[5];
		String line;
		
		while((line = this.stream.readLine()) != null){
			lineItems = line.split(",");
			list.add(lineItems);
		}
		return list;
	}
	
	/**
	 * Returns an instance of CsvReader, if no instance exists, an instance will be created.
	 * This needs to be called, to make this class a singleton.
	 * @return an object of CsvReader
	 */
	public static CsvReader getInstance(){
		if(instance == null){
			instance = new CsvReader();
		}
		return instance;
	}
}
